<?php
namespace app\api\controller;
use think\Request;
use think\Validate;
use think\Controller;
use think\Db;
class CommonController extends Controller
{
    protected $user_id;
    protected $staff_number;
    protected $staff_duty;
    protected $page = 1;
    protected $limit = 5;

    public function _initialize()
    {
        header("Access-Control-Allow-Origin: *");
        header('Access-Control-Allow-Headers:Authorization');
        header("Access-Control-Allow-Methods: GET, POST, DELETE");
        header("Access-Control-Allow-Credentials: true");
        header("Access-Control-Allow-Headers: Content-Type, X-Requested-With, Cache-Control,Authorization");
        error_reporting(E_ERROR | E_PARSE); // 定义错误级别
    }


     /**
     * token验证
     * @param string $token 秘钥
     * @return strting  
     */
    public function verifyToken($token='')
    {
        if ( empty($token) || $token == '' || $token == null ) return returnJson(400, 'token_key不能为空'); // 验证token不能为空
        $tokenInfo = Db::name('ims_member')->where('token_key', $token)->field('id,token_key,staff_number,staff_duty,token_time,status')->find();
        if ( !$tokenInfo ) return returnJson(2002, $this->errTips[2002]); // 验证token是否存在
        if ( $tokenInfo['status'] != 1 ) return returnJson(2003, $this->errTips[2003]); // 用户被禁用
        if ( !isset($tokenInfo['token_time']) || $tokenInfo['token_time'] <= time() ) return returnJson(2001, $this->errTips[2001]); // 验证token时效
        Db::name('ims_member')->where('id', $tokenInfo['id'])->update(['token_time' => time()+1800]); // 修改token时效
        $this->user_id = $tokenInfo['id'];
        $this->staff_number = $tokenInfo['staff_number'];
        $this->staff_duty = $tokenInfo['staff_duty'];
        return 1111;
    }

    /**
     * [verifyDuty 验证权限]
     * @param  [string] $msg [权限标志]
     * @return [type]      [description]
     */
    public function verifyDuty($msg, $staff_duty='')
    {
        if ( empty($msg) ) return returnJson(400, '缺少参数');
        if ( empty($staff_duty) ) $staff_duty = $this->staff_duty;
        $duty = Db::name('ims_member_duty')->where('duty', "{$staff_duty}")->field('duty, is_meeting, is_straming')->find();
        if ( $msg == 'meeting' && $duty['is_meeting'] != 1 ) {
            return returnJson(400, '无发起会议权限');
        } elseif ( $msg == 'straming' && $duty['is_straming'] != 1 ) {
            return returnJson(400, '无发起培训权限');
        }
        return 1111;
    }

    /**
     * [userInfoOne 获取用户信息]
     * @param  [string] $[staff_number] [<员工工号>]
     * @return [int] [员工ID]
     */
    public function userInfoOne($staff_number)
    {
        if ( empty($staff_number) ) return false;
        // 获取员工资料
        $userInfo = json_decode($this->post(STAFF_USER_ONE_USER, staffTokenDataALL('PXS000301', 'PxS000301xuZHenG', $staff_number)));
        $dataSave['staff_number']   = $userInfo->user_id;
        $user_id = '';
        if ($dataSave['staff_number'] != '' && $dataSave['staff_number'] != null) { 
            $dataSave['staff_name']     = $userInfo->user_name;
            $dataSave['staff_duty']     = $userInfo->user_duty;
            $dataSave['staff_pic']      = $userInfo->user_picture;
            $dataSave['staff_deptname'] = $userInfo->deptname;
            $dataSave['staff_deptid']   = $userInfo->deptid;
            if ( $user_id=Db::name('ims_member')->where('staff_number',$userInfo->user_id)->value('id') ) {
                $dataSave['update_time']     = date('Y-m-d H:i:s', time());
                Db::name('ims_member')->where('staff_number', $userInfo->user_id)->update($dataSave); // 更新数据
            } else {
                $dataSave['create_time']     = date('Y-m-d H:i:s', time());
                $user_id=Db::name('ims_member')->insertGetId($dataSave); // 添加数据
            }
        }
        return $user_id;
    }

    /**
     * [delFile 删除文件]
     * @param  [string] $path [路径]
     * @param  [string] $file [文件名]
     * @return [type]       [description]
     */
    protected function delFile($path, $file)
    {
        if (file_exists($file)) {
            chmod($file, 0777);
            return unlink($file);// 删除文件
        }
    }

    /**
     * POST请求
     * @param string $uri 请求地址
     * @param array $data 请求参数
     * @return bool
     */
    public function post($url, $data)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if(!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    /**
     * 前台插入请求记录
     * @param   $[content] [<操作内容>]
     * @param   $[datas] [<操作数据>]
     */
    public function traceLog($content, $datas='')
    {
        if ( empty($content) ) return false;
        $data['user_id'] = $this->user_id;
        $data['number'] = $this->staff_number ? $this->staff_number : '游客';
        $data['content'] = htmlentities($content);
        $data['datas'] = serialize($datas);
        $data['is_app'] = 'home';
        $data['ip'] = request()->ip();
        $data['create_time'] = date("Y-m-d H:i:s", time());

        Db::name('ims_trace_logs')->insert($data);
    }

    /**
     * 鉴权函数
     * @param  [string] $[url] [<推流、播流域名>]
     * @param  [int] $[time] [<过期时间>]
     * @param [string] $[key] [<主键>]
     * @param [string] $[filename] [<模板名>]
     */
    function PrivateKeyA($url, $time=0, $key='', $filename=''){
      $time=strtotime("+8 hours");
      $key=$key;
      $domain=$url;
      $filename=$filename;
      //$sstring = "URI-Timestamp-rand-uid-PrivateKey"
      $sstring = $filename."-".$time."-0-0-".$key;
      $md5=md5($sstring);
      $auth_key="auth_key=".$time."-0-0-".$md5;
      $url=$domain.$filename."?".$auth_key;
      return $url;
    }

    /**
     * [GetDistance 获取2点之间的距离]
     * @param [string] $lat1 [经度1]
     * @param [string] $lng1 [纬度1]
     * @param [string] $lat2 [经度2]
     * @param [string] $lng2 [纬度2]
     * @return [int] [<距离，单位：m>]
     */
    public function GetDistance($lat1, $lng1, $lat2, $lng2){
        $earthRadius = 6367000; 
        $lat1 = ($lat1 * pi() ) / 180;
        $lng1 = ($lng1 * pi() ) / 180;
        $lat2 = ($lat2 * pi() ) / 180;
        $lng2 = ($lng2 * pi() ) / 180;
        $calcLongitude = $lng2 - $lng1;
        $calcLatitude = $lat2 - $lat1;
        $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);  
        $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
        $calculatedDistance = $earthRadius * $stepTwo;
        // $this->GetDistance('22.830311', '113.721802', '22.83062' , '113.704193')

        return round($calculatedDistance);
    }

    /**
     * [GetScore 评分]
     * @param [int] $vm_id  [直播ID]
     * @param [float] $score  [分数]
     * @param [int] $is_vm  [标志；1-培训，2-会议]
     * @param [int] $author [作者]
     */
    protected function GetScore($vm_id, $score, $is_vm, $author)
    {   
        if ( empty($vm_id) || empty($score) || empty($is_vm) || empty($author) ) return false;
        // 添加平均分
        $data['vm_id'] = $vm_id;
        $data['user_id'] = $this->user_id;
        $data['score'] = $score;
        $data['is_vm'] = $is_vm;
        $data['create_time'] = date('Y-m-d H:i:s', time());
        $res = DB::name('ims_live_score')->insert($data);
        // 添加成功后计算直播平均份
        if ( $res ) {
            // 修改直播平均分
            $vmAvgScore = DB::name('ims_live_score')->where('vm_id', $vm_id)->where('is_vm', $is_vm)->avg('score');
            if ( $is_vm == 1 ) {
                DB::name('ims_straming_live')->where('id', $vm_id)->update(['score_mean'=>$vmAvgScore]);
            } elseif ( $is_vm == 2 ) {
                DB::name('ims_meeting_live')->where('id', $vm_id)->update(['score_mean'=>$vmAvgScore]);
            }

            // 修改作者平均分
            $sAvgScore = DB::name('ims_straming_live')->where('user_id', $author)->where('status', 5)->avg('score_mean');
            $mAvgScore = DB::name('ims_meeting_live')->where('compere_id', $author)->where('status', 5)->avg('score_mean');
            if ( $sAvgScore ) {
                $totalAvgScore = $sAvgScore;
            } elseif ( $mAvgScore ) {
                $totalAvgScore = $mAvgScore;
            } elseif ( $sAvgScore && $mAvgScore ) {
                $totalAvgScore = ($sAvgScore+$mAvgScore) / 2;
            }
            Db::name('ims_member')->where('id', $author)->update(['vedio_score'=>$totalAvgScore]);
            
        }
        return true;
    }

    /*----------------定义错误号-------------------*/
     protected $errTips = [
        //公共返回码
        2001 => '账号未登录或登录已过期',
        2002 => '账号不存在',
        2003 => '账号被禁用',

        2004 => '非法操作',
        2005 => '不能频繁发表评论',
        2006 => '标题字数长度不在限定范围内',
        2007 => '内容字数长度不在限定范围内',
        2008 => '关键词字数长度不在限定范围内',
        2009 => '每个关键词最多4个字长度或者“,”号错误',

        //数据操作返回码
        3001 => '修改（更新）失败',
        3002 => '写入数据失败',
        3003 => '数据为空',
        3004 => '删除失败',

        //请求参数或if else判断等返回码
        4001 => '请求参数长度不合理',
        4002 => '请求参数必填选项不能为空',
        4003 => '手机号码格式不正确',
        4004 => '请求参数必须为数字',
        4005 => '最大值不符合规定',
        4006 => '最小值不符合规定',
        4007 => '不能为小数',
        4008 => '请求参数不在限定范围内',
        4009 => 'token过期或无效',
        4010 => '评论字数不在设定范围内',

        //短信、验证码返回码
        5001 => '验证码不正确或失效',
        5002 => '验证码长度必须为'.VERIFY_LENGTH.'位',
        5003 => '验证码未失效，请不要重复获取',
        5004 => '验证码仅支持数字',
        5005 => '验证码必填项',

        // 图片上传
        6001 => '请上传图片',
        6002 => '图片上传出错',

        //结果返回码
        200 => 'success',
        400 => 'false'
    ];


    public function createNonceStr($length = 6)
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }



}